#include "function_base_test.h"
#include "viml/compiler.h"
#include "viml/vm.h"
#include <gtest/gtest.h>

namespace viml {

/**
 * 复杂函数调用测试
 */
class FunctionComplexTest : public FunctionCallTestBase {
protected:
    void SetUp() override {
        FunctionCallTestBase::SetUp();
    }
};

// FC-101: 测试函数作为返回值
TEST_F(FunctionComplexTest, FunctionAsReturnValue) {
    std::string source = R"(
function create_multiplier(factor)
    function multiplier(x)
        return x * factor
    endfunction
    return multiplier
endfunction

let doubler = create_multiplier(2)
let result = doubler(5)
echo result
)";
    
    compileAndExecute(source, "FunctionAsReturnValue");
}

// FC-102: 测试控制流与函数集成
TEST_F(FunctionComplexTest, ControlFlowIntegration) {
    std::string source = R"(
function conditional_call(flag)
    if flag
        echo "Flag is true"
    else
        echo "Flag is false"
    endif
endfunction

conditional_call(1)
conditional_call(0)
)";
    
    compileAndExecute(source, "ControlFlowIntegration");
}

// FC-103: 测试嵌套作用域访问
TEST_F(FunctionComplexTest, NestedScopeAccess) {
    std::string source = R"(
let global_var = "global"

function outer()
    let outer_var = "outer"
    function inner()
        let inner_var = "inner"
        echo global_var  " 访问全局变量
        echo outer_var   " 访问外层函数变量
        echo inner_var   " 访问本层变量
    endfunction
    inner()
endfunction

outer()
)";
    
    compileAndExecute(source, "NestedScopeAccess");
}

// FC-104: 测试循环中的函数定义和调用
TEST_F(FunctionComplexTest, FunctionInLoop) {
    std::string source = R"(
function make_counter()
    let count = 0
    function counter()
        count = count + 1
        return count
    endfunction
    return counter
endfunction

let counter = make_counter()
let result1 = counter()
let result2 = counter()
let result3 = counter()
echo result1
echo result2
echo result3
)";
    
    compileAndExecute(source, "FunctionInLoop");
}

// FC-105: 测试函数列表
TEST_F(FunctionComplexTest, FunctionList) {
    std::string source = R"(
function add(a, b)
    return a + b
endfunction

function multiply(a, b)
    return a * b
endfunction

" 创建函数列表（注意：这可能需要VM支持）
let operations = [add, multiply]
let result1 = operations[0](3, 4)  " add(3, 4)
let result2 = operations[1](3, 4)  " multiply(3, 4)
echo result1
echo result2
)";
    
    compileAndExecute(source, "FunctionList");
}

// FC-106: 测试函数字典
TEST_F(FunctionComplexTest, FunctionDict) {
    std::string source = R"(
function add(a, b)
    return a + b
endfunction

function subtract(a, b)
    return a - b
endfunction

" 创建函数字典（注意：这可能需要VM支持）
let ops = {'add': add, 'sub': subtract}
let result1 = ops['add'](10, 5)
let result2 = ops['sub'](10, 5)
echo result1
echo result2
)";
    
    compileAndExecute(source, "FunctionDict");
}

} // namespace viml